<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { login } from '@/api'
import AuthBackground from '../components/AuthBackground.vue'

const router = useRouter()
const form = reactive({
  username: '',
  password: '',
  agreement: false
})

const pageLogin = async () => {
  if (!form.agreement) {
    ElMessage.warning('Please agree to the service terms')
    return
  }
  
  try {
    const data = await login({
      username: form.username,
      password: form.password
    })
    
    // 存储token和用户信息
    localStorage.setItem('token', data.token)
    localStorage.setItem('userInfo', JSON.stringify({
      id: data.id,
      username: data.username,
      role: data.role
    }))
    
    ElMessage.success('Login successful')
    
    // 如果有重定向地址，则跳转到重定向地址
    const redirect = router.currentRoute.value.query.redirect
    router.push(redirect || '/analysis/core')
  } catch (error) {
    console.error('Login failed:', error)
  }
}
</script>

<template>
  <AuthBackground>
    <h2 class="title">Login</h2>
    <el-form :model="form" label-position="top">
      <el-form-item label="Username">
        <el-input v-model="form.username" placeholder="Enter your username" />
      </el-form-item>
      
      <el-form-item label="Password">
        <el-input v-model="form.password" type="password" placeholder="Enter your password" />
      </el-form-item>
      
      <el-form-item>
        <el-checkbox v-model="form.agreement">
          I accept the service regulations
        </el-checkbox>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="pageLogin" style="width: 100%">
          Login
        </el-button>
      </el-form-item>
    </el-form>
    
    <div class="register-link">
      Don't have an account? 
      <router-link to="/register">Create your account</router-link>
    </div>
  </AuthBackground>
</template>

<style scoped>
.title {
  text-align: center;
  color: #1890ff;
  margin-bottom: 2rem;
}

.register-link {
  text-align: center;
  margin-top: 1rem;
  color: #666;
}

.register-link a {
  color: #1890ff;
  text-decoration: none;
}

.register-link a:hover {
  text-decoration: underline;
}
</style> 